import 'dart:developer';
import 'dart:io';

import 'package:flutter_multi_env/models/city_model.dart';
import 'package:flutter_multi_env/utils/utils.dart';
import 'package:flutter_multi_env/utils/https_utils.dart';

import '../models/package_info_model.dart';
import '../models/server_model.dart';
import '../urls/global_url.dart';
import '../utils/code_utils.dart';

/// 全局请求类
class RequestGlobal {
  ///
  /// @description：获取服务器地址
  ///
  /// @return：服务器信息模型
  ///
  static Future<ServerData?> requestServeData() async {
    // 获取本地 app 信息
    PackageInfoData packageInfoData = await Utils.cnm_getPackageInfo();

    // 设置请求参数
    Map<String, Object> parameters = {
      'businessCode': 'StudShuttleBus',
      'appType': Platform.isIOS ? '2' : '1',
      "versionCode": packageInfoData.buildNumber ?? '',
    };

    // 发起请求
    ServerData? serverData;
    try {
      BaseResponseModel? response = await HttpsUtils.post(
        ApiGlobal.getServiceUrl,
        parameters: parameters,
      );

      // 响应
      if (response != null && response.code == Code.success.value) {
        serverData = ServerData.fromMap(response.data ?? {});
        // 配置请求域名
        HttpsUtils.serverBaseUrl = serverData.serviceUrl ?? '';
      }
    } catch (e) {
      log('抛异常：$e');
    }
    return serverData;
  }

  ///
  /// @description：获取城市列表
  ///
  /// @return：城市列表Data模型
  ///
  static Future<List<CityModel>> requestAllCitysData() async {
    List<CityModel> citys = [];

    try {
      BaseResponseModel? response = await HttpsUtils.post(ApiGlobal.getAllCitysUrl);

      if (response != null && response.code == Code.success.value) {
        CityData data = CityData.fromList(response.data ?? []);
        citys = data.cityList;
      }
    } catch (e) {
      log('抛异常：$e');
    }
    return citys;
  }
}
